<!-- 分享链接 -->
<template>
  <div class="grid" ref="shareLinkView">
    <!-- 头部导航 -->
    <div class="col-12">
      <CommonHeaderToolBar/>
    </div>
    <!-- 左侧导航栏 -->
    <div class="col-2">
      <LeftMenu/>
    </div>
    <!-- 链接 card -->
    <div class="col-10" style="height: 346px">
      <h3 style="margin-block: 0">当前共有{{ total }}个网站被分享</h3>
      <ShareLinkCard v-for="(item, index) of shareLinks"
                     :key="index"
                     :collect="item.collect"
                     :image="item.linkSrc"
                     :link="item.linkUrl"
                     :title="item.linkName"
                     :desc="!item.linkDesc || item.linkDesc === '' ? '作者没对它做任何介绍哦~' : item.linkDesc"
                     :tags="item.linkTags.split(',')"
                     class="m-2"
                     style="width: 23%; height: 100%;"/>
    </div>
    <!-- 上传面板 -->
    <ToolButton class="upload-tool-btn" customer-siderbar-class="upload-siderbar" :affix-target-dom="shareLinkView">
      <template #sidebarContent>
        <div class="grid">
          <div class="col-12 mt-2">
            <!-- 链接名称 -->
            <div class="p-inputgroup">
              <span ref="chips__selected__addon" class="p-inputgroup-addon" style="width: 100px">
                链接名称
              </span>
              <InputText id="linkName" class="w-full" type="text" placeholder="输入链接的名称"
                         v-model="shareLinkParams.linkName"/>
            </div>
            <!-- 链接地址 -->
            <div class="p-inputgroup mt-3">
              <span ref="chips__selected__addon" class="p-inputgroup-addon" style="width: 100px">
                链接地址
              </span>
              <InputText id="linkHref" class="w-full" type="text" placeholder="输入访问链接地址"
                         v-model="shareLinkParams.linkUrl"/>
            </div>
            <!-- 链接标签 -->
            <div class="mt-3">
              <ChipsSelected
                  addon="链接标签"
                  placeholder="记得给链接上几个标签哦"
                  filter
                  :max="5"
                  :items="['前端', '后端', 'CSS', '论坛', '优秀网站']"
                  @change="chipsSelectedChangeHandler"
                  :default-selected="'2'"/>
            </div>
            <!-- 链接封面 -->
            <div class="p-inputgroup mt-3">
              <span ref="chips__selected__addon" class="p-inputgroup-addon" style="width: 100px">
                链接封面
              </span>
              <InputText id="linkHref" class="w-full" type="text" placeholder="补充链接封面，如果没有可以上传图片哦~"
                         v-model="shareLinkParams.linkSrc"/>
            </div>
            <!-- 上传图片 -->
            <div class="p-float-label mt-3">
              <FileUpload name="files" url="http://127.0.0.1:9999/file/directCloud"
                          @upload="onTemplatedUpload($event)"
                          @select="onSelectedFiles"
                          @before-upload="onBeforeUpload"
                          :multiple="false"
                          :maxFileSize="8*1024*1024"
                          accept="image/*">
                <!-- 头部 -->
                <template #header="{ chooseCallback, uploadCallback, clearCallback, files }">
                  <div class="flex flex-wrap justify-content-between align-items-center flex-1 gap-2">
                    <div class="flex gap-2">
                      <Button @click="onSelectedBtnHandler(files, chooseCallback())" icon="pi pi-images"
                              class="p-button-rounded"></Button>
                      <Button @click="uploadEvent(uploadCallback)" icon="pi pi-cloud-upload"
                              class="p-button-rounded p-button-success"
                              :disabled="!files || files.length === 0"></Button>
                      <Button @click="clearCallback()"
                              icon="pi pi-times"
                              class="p-button-rounded p-button-danger"
                              :disabled="!files || files.length === 0"></Button>
                    </div>
                  </div>
                </template>
                <!-- 上传 -->
                <template #content="{ files, uploadedFiles, removeUploadedFileCallback, fileRemoveCallback }">
                  <!-- 准备上传界面 -->
                  <div v-if="files.length > 0">
                    <div class="flex flex-wrap justify-content-center">
                      <div v-for="(file) of files" :key="file.name + file.type + file.size"
                           class="card m-0 px-6 flex flex-column align-items-center gap-3">
                        <div>
                          <Image role="presentation" :alt="file.name" :src="file.objectURL" width="100" class="shadow-2"
                                 preview></Image>
                        </div>
                        <span class="font-semibold">{{ file.name }}</span>
                        <div>{{ formatSize(file.size) }}</div>
                        <Badge value="准备上传" severity="warning"/>
                      </div>
                    </div>
                  </div>
                  <!-- 上传完毕界面 -->
                  <div v-if="uploadedFiles.length > 0">
                    <div class="flex flex-wrap justify-content-center">
                      <div v-for="(file, index) of uploadedFiles" :key="file.name + file.type + file.size"
                           class="card m-0 px-6 flex flex-column align-items-center gap-3">
                        <div>
                          <Image role="presentation" :alt="file.name" :src="file.objectURL" width="100" class="shadow-2"
                                 preview></Image>
                        </div>
                        <span class="font-semibold">{{ file.name }}</span>
                        <div>{{ formatSize(file.size) }}</div>
                        <Badge value="上传完毕" class="mt-3" severity="success"/>
                      </div>
                    </div>
                  </div>
                </template>
                <!-- 空文件状态 -->
                <template #empty>
                  <div class="flex align-items-center justify-content-center flex-column">
                    <i class="pi pi-cloud-upload border-2 border-circle p-5 text-8xl text-400 border-400"/>
                    <p class="mt-4 mb-0">点击按钮选择图片或者把图片拉到此处都可以哦</p>
                  </div>
                </template>
              </FileUpload>
            </div>
            <!-- 链接介绍 -->
            <div class="mt-3">
              <Textarea id="linkArea" class="w-full" rows="4" :autoResize="true" type="text" placeholder="简要介绍下你分享的链接吧~"
                        v-model="shareLinkParams.linkDesc"/>
            </div>
            <!-- 提交按钮 -->
            <div class="mt-5 text-right">
              <Button label="提交审核" class="p-button-secondary p-button-text" @click="shareLinkSubmitHandler"></Button>
            </div>
          </div>
        </div>
      </template>
    </ToolButton>
  </div>
</template>

<script lang="ts" setup>
/** JS */
import {Ref, ref, reactive, onMounted} from 'vue';
import {ShareLinkEntity, ShareLinkResponse} from '@/interface/link/share/entity/ShareLinkEntity';
import {UserMsg} from '@/interface/user/entity/UserEntityInterface';
import {ShareLinkService, Paging} from '@/utils/ApiRequest';
import toast from '@/utils/Toast';
import Cache from '@/utils/Cache';
/** 组件 */
import LeftMenu from '@/components/menu/LeftMenu.vue';
import CommonHeaderToolBar from '@/components/toolbar/CommonHeaderToolBar.vue';
import ShareLinkCard from '@/components/card/ShareLinkCard.vue';
import ToolButton from '@/components/button/ToolButton.vue';
import ChipsSelected from '@/components/input/ChipsSelected.vue';
import FileUpload from 'primevue/fileupload';
import Image from 'primevue/image';
import Badge from 'primevue/badge';

/** 数据初始化 */
const cache = new Cache(), userMsg: UserMsg = cache.get('userMsg'), shareLinkService = new ShareLinkService();
/** 元素钩子 */
const shareLinkView = ref(null);
/** 提交链接属性 */
const shareLinkParams: ShareLinkEntity = reactive({
  linkName: '',
  linkSrc: '',
  linkUrl: '',
  linkDesc: '',
  linkTags: '',
  nickname: userMsg?.nickname
});
const files = ref([]),
    totalSize = ref(0),
    totalSizePercent = ref(0)
const onSelectedFiles = (event) => {
      if (event.files.length > 1) {
        let i = event.files.length - 1;
        event.files.splice(0, 1, event.files[i]);
        event.files.splice(i, 1);
      }
      files.value = event.files;
      files.value.forEach((file) => {
        totalSize.value += parseInt(formatSize(file.size));
      });
    },
    onSelectedBtnHandler = (files, callback) => {
      callback;
    },
    onBeforeUpload = (e) => {
      (e.formData as FormData).append('path', 'share/thumb');
      return e;
    },
    uploadEvent = (callback) => {
      totalSizePercent.value = totalSize.value / 10;
      callback();
    },
    onTemplatedUpload = (res) => {
      let xhr = (res.xhr) as XMLHttpRequest;
      if (xhr) {
        let response = JSON.parse(xhr.response);
        if (response.code === 0) {
          shareLinkParams.linkSrc = response.data[0];
          toast.success('恭喜哦~', '封面上传成功了!', 3000);
        } else {
          toast.error('完了完了', response.msg, 3000);
        }
      }
      totalSize.value = 0;
      totalSizePercent.value = 0;
    };
/** 格式化大小 */
const formatSize = (bytes) => {
  if (bytes === 0) {
    return '0 B';
  }
  let k = 1000,
      dm = 3,
      sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
      i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

/** 监听选择的标签 */
const chipsSelectedChangeHandler = (val) => {
  shareLinkParams.linkTags = val.join(',');
}
/** 提交审核 */
const shareLinkSubmitHandler = async () => {
  if (userMsg) {
    let txt = '';
    var pattern = /^http:///([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$/;
    if (pattern.test(shareLinkParams.linkUrl)) {
      toast.error('提交审核失败', '请确保链接格式正确', 1500);
      return;
    }
    for (let key in shareLinkParams) {
      let param = shareLinkParams[key];
      if (!param || param.trim() == '') {
        if (key === 'linkUrl') {
          txt = '链接地址';
        } else if (key === 'linkSrc') {
          txt = '链接封面图片'
        } else if (key === 'linkTags') {
          txt = '链接介绍标签'
        } else if (key === 'linkName') {
          txt = '链接标题'
        }
        toast.error('提交审核失败', `需要填写${txt}才能提交哦!~`, 1500);
        return;
      }
    }
    let res = await shareLinkService.submit(shareLinkParams);
    if (res && res.code === 0) {
      toast.success('提交成功啦~', '管理员审核通过后会通知给您的哦！(●\'◡\'●)', 1500);
    }
  }
}

let paging: Paging = {page: 0, limit: 10}, shareLinks: Ref<ShareLinkResponse[]> = ref([]);
let total = ref(0);
onMounted(async () => {
  let res = await shareLinkService.list(paging);
  if (res && res.code === 0) {
    total.value = res.data.total;
    shareLinks.value = res.data.data;
  }
})
</script>

<style scoped>

</style>
